<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>工单上传</title>
	<script src="//static.cloudbase.net/cloudbase-js-sdk/1.7.2/cloudbase.full.js"></script>
	<style>
		* {
			margin: 0;
			padding: 0;
		}

		body {
			padding: 10px;
		}

		.flex {
			display: flex;
		}

		.gap-5 {
			gap: 1rem;
		}

		.log {
			height: 500px;
			overflow: auto;
			border: 1px solid #ccc;
			border-radius: 5px;
			margin-top: 10px;
		}
	</style>
</head>

<body>
	<div class="flex gap-5">
		<div class="flex">
			<label for="collection">选择数据库：</label>
			<select name="" id="collection"></select>
		</div>
		<div class="flex gap-5">
			<label for="file">选择文件：</label>
			<input id="file" type="file" name="file" accept=".csv" />
		</div>
		<button id="upload">上传</button>
		<!-- <button id="checkCount">检查</button>
		<button id="delete">删除</button> -->
	</div>
	<div id="log" class="log"></div>
	<script>
		var collections = [
			{ value: "tousu_zt", label: "投诉在途" },
			{ value: "tousu_xp", label: "投诉新派" },
			{ value: "tousu_gd", label: "投诉归档" },

			{ value: "kuandai_zt", label: "宽带在途" },
			{ value: "kuandai_gd", label: "宽带归档" },
			{ value: "kuandai_xp", label: "宽带新派" },

			{ value: "xinyewu_zt", label: "新业务在途" },
			{ value: "xinyewu_gd", label: "新业务归档" },
			{ value: "xinyewu_xp", label: "新业务新派" },
		];

		const colleciton_selector = document.querySelector("#collection");
		const fileELe = document.querySelector("#file");
		let currentDate = '';
		let currentData = [];
		fileELe.addEventListener('change', e => {
			const file = e.target.files[0];

			const fr = new FileReader()
			fr.onload = e => {
				let text = e.target.result;

				let rows = text.split('\n')
				let header = rows[0]
				let keys = header.split(',').map(i => i.trim())
				let dates = new Set();
				let data = rows.slice(1, rows.length - 1).map(textLine => {
					let rowData = textLine.replaceAll('\r', '').split(',');
					let obj = {};
					keys.forEach((k, i) => {
						obj[k] = rowData[i]
						if (k === 'date' || k === '日期' || k === "paidanshijian") {
							obj[k] = +rowData[i]
						}
						if (k === 'date') {
							dates.add(+rowData[i])
						}
					})
					return obj
				})
				dates = [...dates]
				console.log(data)
				log(`当前数据日期为【${dates.join(',')}】`)
				log(`当前数据数据为【${data.length}】`)
				if (dates.length > 1) {
					log(`当前数据包含多天数据，请检查`)
				} else {
					currentData = data;
					currentDate = dates[0]
				}
			}

			fr.readAsText(file)
		})
		colleciton_selector.innerHTML = `
        <option value="">-</option>
        ${collections.map((item) => {
			return `<option value="${item.value}">${item.label}</option>`;
		})}
      `;

		let currentCollection = null;
		colleciton_selector.onchange = e => {
			currentCollection = collections.find(i => i.value === e.target.value)
			e.target.value ? log(`数据库已选中<i style="color:red;">【${currentCollection.label}】</i>`) : log(`未选中任何数据库`)
		}
		const cloudApp = cloudbase.init({
			env: "cnycharts-4giqg3kn6179e262", // 上海环境id
			region: "ap-shanghai",
		});

		const logEle = document.querySelector("#log");
		function log(msg) {
			let msgString = `<p>${msg}</p>`;
			let oldMsg = logEle.innerHTML;
			logEle.innerHTML = `${oldMsg}${msgString}`;
		}

		function checkCount(collection, date) {
			return callFunction({
				target: "action/checkCount",
				collection,
				date: date,
			});
		}

		function deleteData(collection, date) {
			return callFunction({
				target: "action/deleteData",
				collection,
				date: date,
			});
		}

		const uploadBtn = document.querySelector('#upload')
		uploadBtn.addEventListener('click', async e => {

			const collection = colleciton_selector.value;
			if (!collection) {
				alert('请先选择数据库')
				return;
			}
			if (!currentData.length || !currentDate) {
				alert('请先选择文件')
				return;
			}
			e.target.disabled = true;
			let rs = await checkCount(collection, currentDate)
			log(`【${currentCollection.label}】数据库日期为【${currentDate}】的数据有【${rs.total}】条`)
			if(confirm(`【${currentCollection.label}】数据库日期为【${currentDate}】的数据有【${rs.total}】条,是否覆盖更新这【${rs.total}】条数据`)){
				if(rs.total){
					let delRs = await deleteData(collection, currentDate)
					log(`已删除【${currentCollection.label}】数据库【${currentDate}】的数据【${delRs.deleted}】条`)
				}

				let upRs = await uploadData(collection, currentData)
				log(`已更新${upRs.ids.length}条数据`)
				console.log(upRs)
				e.target.disabled = false;
			} else {
				e.target.disabled = false;
			}
		})
		function uploadData(collection, data) {
			return callFunction({
				target: "action/uploadData",
				collection,
				data,
			});
		}

		function callFunction(data) {
			return cloudApp
				.callFunction({
					name: "aggregate",
					data: data,
				})
				.then((res) => {
					return Promise.resolve(res.result);
				})
				.catch(console.error);
		}
	</script>
</body>

</html>